﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace fabao.Common.Util
{
    public class MD5Helper
    {
        /// <summary>
        /// 字典排序拼接
        /// </summary>
        /// <param name="paramsmap"></param>
        /// <returns></returns>
        public static string Getparamsrc(Dictionary<string, string> paramsmap)
        {
            var vdic = (from objdic in paramsmap orderby objdic.Key ascending select objdic);
            StringBuilder str = new StringBuilder();
            foreach (KeyValuePair<string, string> kv in vdic)
            {
                string pkey = kv.Key;
                if (!string.IsNullOrEmpty(pkey))
                {
                    if (pkey.Equals("sign"))
                    {
                        continue;
                    }
                    string pvalue = kv.Value;
                    str.Append(pkey + "=" + pvalue + "&");
                }
            }
            string result = str.ToString().Substring(0, str.ToString().Length - 1);
            return result;
        }

        /// <summary>
        /// HmacSha1加密
        /// </summary>
        /// <param name="plaintext"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public static string HmacSHA1(string plaintext, string secretKey)
        {
            var key = Encoding.UTF8.GetBytes(secretKey);
            var hmac1 = new HMACSHA1(key);
            var data = Encoding.UTF8.GetBytes(plaintext);
            var hash = hmac1.ComputeHash(data);
            return Convert.ToBase64String(hash);
        }

        /// <summary>
        /// Md5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5(object InitData)
        {
            string SecretKey = "qwertyuiopasdfghjklzxcvbnm";
            return EncryptData(InitData, SecretKey);
        }
        
        /// <summary>
        /// DES对称加密方法
        /// </summary>
        /// <param name="InitData">原始待加密数据</param>
        /// <param name="SecretKey">加密密钥</param>
        public static string EncryptData(object InitData, string SecretKey)
        {
            try
            {
                string newSecretKey = MD5Encrypt(SecretKey + "ht").Substring(16, 8);
                using (var des = DES.Create())
                {

                    //把字符串放到byte数组中    
                    Byte[] inputByteArray = Encoding.Default.GetBytes(InitData.ToString());
                    //建立加密对象的密钥和偏移量
                    des.Key = ASCIIEncoding.ASCII.GetBytes(newSecretKey);
                    //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 
                    des.IV = ASCIIEncoding.ASCII.GetBytes(newSecretKey);
                    //使得输入密码必须输入英文文本
                    MemoryStream ms = new MemoryStream();
                    CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    StringBuilder ret = new StringBuilder();
                    foreach (Byte b in ms.ToArray())
                    {
                        ret.AppendFormat("{0:X2}", b);
                    }
                    ret.ToString();
                    return ret.ToString();
                }
            }
            catch
            {
                return "";
            }
        }

        public static string MD5Encrypt(string s)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
                var strResult = BitConverter.ToString(result);
                return strResult.Replace("-", "").ToUpper();
            }
        }

        public static string MD5BitEncrypt(string s)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.Default.GetBytes(s));
                var strResult = BitConverter.ToString(result, 4, 8);
                return strResult.Replace("-", "").ToLower();
            }
        }

        /// <summary>
        /// Md5加密(发送请求时加签)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5ToUpperHelp(string str)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(str);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // 将字节数组转换为十六进制字符串
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2")); // X2 表示转换为大写的十六进制
                }
                return sb.ToString();
            }
        }

        /// <summary>
        /// SHA256加密(不可逆)
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string SHA256Encrypt(string s)
        {
            using (SHA256 sha = SHA256.Create())
            {
                byte [] inputBytes = Encoding.UTF8.GetBytes(s);
                byte [] hashBytes = sha.ComputeHash(inputBytes);
                StringBuilder builder = new StringBuilder();
                for(int i = 0; i < hashBytes.Length; i++)
                {
                    builder.Append(hashBytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }
    }
}
